//
// Created by 11510 on 2024/6/9.
//

#include "Dictionary.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <algorithm>

using std::cin;
using std::cerr;
using std::cout;
using std::endl;
using std::ifstream;
using std::ofstream;
using std::istringstream;
using std::sort;

// 比较函数，用于按字典序比较 Record 对象的 _word 字段
bool compareRecords(const Record* lhs, const Record* rhs) {
    return lhs->_word < rhs->_word;
}

/**
 * 在vector中查找是否存在此单词，存在则频率加一
 * @param word
 * @return
 */
bool Dictionary::isExistThisWordInDict(const string &word){
    for(std::vector<Record*>::iterator it = _dict.begin(); it != _dict.end(); it++){
        if(word.compare((*it)->_word) == 0){
            (*it)->_frequency++;
            return true;
        }
    }
    return false;
}

/**
 * 判断一个string是否是一个合法的单词
 * @param str
 * @return
 */
bool Dictionary::isWord(const std::string& str) {
    // 空字符串不是一个单词
    if (str.empty()) {
        return false;
    }

    // 遍历字符串中的每个字符，检查是否都是字母
    for (char c : str) {
        if (!std::isalpha(static_cast<unsigned char>(c))) {
            return false;
        }
    }

    return true;
}

/**
 * 读取文档并存入vecotr
 * @param filename
 */
void Dictionary::read(const std::string &filename) {
    ifstream ifs;
    ifs.open(filename);


    if(!ifs){
        cerr << "ifstream open file failed" << endl;
        return;
    }

    // 这种方式太慢了
/*    string word;
    while(ifs >> word){
        // if is a word , store to vector
        if(isWord(word)) {
            if(!isExistThisWordInDict(word)){
                Record *record = new Record(word, 1);
                _dict.push_back(record);
            }
        }
    }*/


    /**
     * 应该使用hashmap改进的
     * 这是💩代码⬇
     */
    string line;
    while(getline(ifs,line)){
        istringstream iss(line);
        string word;

        while(iss >> word){
            if(isWord(word)) {
                if(!isExistThisWordInDict(word)){
                    Record *record = new Record(word, 1);
                    _dict.push_back(record);
                }
            }
        }
    }

    /**
     * 字典序
     */
    sort(_dict.begin(), _dict.end(), compareRecords);

}

/**
 * 存储为字典
 * @param filename
 */
void Dictionary::store(const string &filename){
    ofstream ofs(filename);
    if(!ofs){
        cerr << "ifstream open file failed" << endl;
        return;
    }

    for(std::vector<Record*>::iterator it = _dict.begin(); it != _dict.end(); it++){
        ofs << (*it)->_word << ":" << (*it)->_frequency << endl;
    }
}


/**
 * 析构函数
 */
Dictionary::~Dictionary(){
    for(std::vector<Record*>::iterator it = _dict.begin(); it != _dict.end(); it++){
        delete *it;
    }
}